<template>
  <div class="search-app">
    <!-- 搜索框 -->
    <div class="search-bar">
      <input
          v-model="keyword"
          class="search-input"
          placeholder="请输入商家/菜品关键词"
          @keyup.enter="handleSearch"
      />
      <el-icon class="search-icon" @click="handleSearch">
        <Search />
      </el-icon>
    </div>

    <!-- 错误提示 -->
    <div v-if="errorMessage" class="error-state">
      <el-empty :description="errorMessage" :image-size="200">
        <template #image>
          <el-icon color="#F56C6C" :size="60">
            <Warning />
          </el-icon>
        </template>
      </el-empty>
    </div>

    <!-- 搜索结果 -->
    <div class="search-results" v-if="!errorMessage">
      <h3 class="section-title">搜索结果</h3>
      <div v-if="businessList.length > 0" class="business-list">
        <el-card
            v-for="business in businessList"
            :key="business.businessId"
            class="business-card"
            shadow="hover"
            @click="goToBusiness(business.businessId)"
        >
          <div class="business-content">
            <div class="business-image">
              <img :src="business.head" alt="商家图片" class="business-img">
            </div>
            <div class="business-info">
              <h4 class="business-name">{{ business.businessName }}</h4>
              <p class="business-address" style="text-align: center">
                <el-icon><Location /></el-icon>
                {{ business.address }}
              </p>
              <div class="business-rating">
                <el-rate
                    v-model="business.rating"
                    disabled
                    show-score
                    text-color="#ff9900"
                    score-template="{value}分"
                    :max="5"
                />
              </div>
            </div>
          </div>
        </el-card>
      </div>
      <div v-else class="empty-state">
        <el-empty description="没有找到相关商家" />
      </div>
    </div>
  </div>
</template>

<script setup>
import {ref, onMounted} from 'vue'
import {useRouter} from 'vue-router'
import {
  Search,
  Location,
  Warning
} from '@element-plus/icons-vue'

const router = useRouter()
const keyword = ref('')
const errorMessage = ref('')
const businessList = ref([])

const handleSearch = () => {
  if (keyword.value.trim()) {
    localStorage.setItem('searchKeyword', keyword.value.trim())
    fetchSearchResults(keyword.value.trim())
  }
}

const goToBusiness = (businessId) => {
  router.push(`/business/${businessId}`)
}

// 获取搜索结果
const fetchSearchResults = async (searchKeyword) => {
  try {
    const token = localStorage.getItem('access_token')
    if (!token) {
      errorMessage.value = '请先登录以获取商家信息'
      router.push('/login')
      return
    }

    const response = await fetch(`http://localhost:8080/business/search/${encodeURIComponent(searchKeyword)}`, {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      }
    })

    if (!response.ok) {
      const errorData = await response.json()
      handleApiError(response.status, errorData)
      return
    }

    businessList.value = await response.json()

  } catch (error) {
    console.error('Error fetching search results:', error)
    errorMessage.value = '服务器连接错误，请检查您的连接或稍后重试'
  }
}

// 处理API错误
const handleApiError = (status, errorData) => {
  switch (status) {
    case 401:
      errorMessage.value = '登录已过期，请重新登录'
      router.push('/login')
      break
    case 403:
      errorMessage.value = '访问被拒绝，您可能没有权限'
      break
    case 503:
      errorMessage.value = '服务暂时不可用，请稍后重试'
      break
    default:
      errorMessage.value = errorData?.message || '服务器繁忙，请稍后重试'
      break
  }
}

// 在组件挂载时获取搜索关键词并执行搜索
onMounted(() => {
  const token = localStorage.getItem('access_token')
  const searchKeyword = localStorage.getItem('searchKeyword')

  if (!token) {
    errorMessage.value = '请先登录以继续操作'
    router.push('/login')
  } else if (searchKeyword) {
    keyword.value = searchKeyword
    fetchSearchResults(searchKeyword)
  }
})
</script>

<style scoped>
.search-app {
  max-width: 800px;
  margin: 0 auto;
  padding: 12px 12px 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
  box-sizing: border-box;
}

/* 错误提示 */
.error-state {
  padding: 40px 0;
  text-align: center;
  background-color: white;
  border-radius: 12px;
  margin-bottom: 20px;
}

/* 搜索栏 */
.search-bar {
  position: relative;
  margin-bottom: 20px;
}

.search-input {
  width: 100%;
  height: 42px;
  border: 1px solid #409eff;
  border-radius: 21px;
  padding: 0 42px 0 15px;
  font-size: 14px;
  outline: none;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
  box-sizing: border-box;
}

.search-icon {
  position: absolute;
  right: 15px;
  top: 50%;
  transform: translateY(-50%);
  font-size: 18px;
  color: #409eff;
  cursor: pointer;
  padding: 8px;
}

/* 区块标题 */
.section-title {
  font-size: 16px;
  color: #333;
  margin: 0 0 15px 8px;
  font-weight: 600;
  display: flex;
  align-items: center;
}

.section-title::before {
  content: "";
  display: inline-block;
  width: 3px;
  height: 14px;
  background: #409eff;
  border-radius: 2px;
  margin-right: 8px;
}

/* 商家列表 */
.search-results {
  margin-bottom: 20px;
}

.business-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.business-card {
  border-radius: 12px;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.3s ease;
  border: none;
}

.business-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);
}

.business-content {
  display: flex;
  padding: 15px;
  gap: 15px;
}

.business-image {
  width: 90px;
  height: 90px;
  flex-shrink: 0;
  border-radius: 8px;
  overflow: hidden;
}

.business-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.business-card:hover .business-img {
  transform: scale(1.05);
}

.business-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  min-width: 0;
  margin-left: 5vw;
}

.business-name {
  margin: 0 0 6px 0;
  font-size: 3vw;
  font-weight: bold;
  color: #333;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.business-address {
  margin: 0 0 8px 0;
  font-size: 2vw;
  color: #666;
  display: flex;
  align-items: center;
  gap: 4px;
}

.business-address .el-icon {
  font-size: 14px;
  color: #999;
}

.business-rating {
  display: flex;
  align-items: center;
}

/* 空状态 */
.empty-state {
  padding: 40px 0;
  text-align: center;
  background-color: white;
  border-radius: 12px;
}

/* 响应式调整 */
@media (max-width: 480px) {
  .business-content {
    padding: 12px;
    gap: 12px;
  }

  .business-image {
    width: 80px;
    height: 80px;
  }

  .business-name {
    font-size: 15px;
  }

  .business-address {
    font-size: 12px;
  }
}

@media (min-width: 600px) {
  .business-card {
    border-radius: 16px;
  }

  .business-image {
    width: 100px;
    height: 100px;
  }

  .business-name {
    font-size: 17px;
  }

  .business-address {
    font-size: 14px;
  }
}
</style>